<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { WebviewWindow } from '@tauri-apps/api/webviewWindow'
import { useAppStore } from '../stores/app'

const isMaximized = ref(false)
const appWindow = WebviewWindow.getCurrent()
const appStore = useAppStore()
let unlistenResize: (() => void) | null = null

const minimizeWindow = async () => {
  try {
    await appWindow.minimize()
  } catch (error) {
    console.error('最小化窗口失败:', error)
  }
}

const toggleMaximize = async () => {
  try {
    const isCurrentlyMaximized = await appWindow.isMaximized()
    if (isCurrentlyMaximized) {
      await appWindow.unmaximize()
      isMaximized.value = false
    } else {
      await appWindow.maximize()
      isMaximized.value = true
    }
  } catch (error) {
    console.error('切换最大化状态失败:', error)
  }
}

const closeWindow = async () => {
  try {
    await appWindow.close()
  } catch (error) {
    console.error('关闭窗口失败:', error)
  }
}

onMounted(async () => {
  // 监听窗口状态变化
  unlistenResize = await appWindow.listen('tauri://resize', async () => {
    isMaximized.value = await appWindow.isMaximized()
  })
})

onUnmounted(() => {
  // 清理事件监听
  if (unlistenResize) {
    unlistenResize()
  }
})
</script>

<template>
  <div class="h-10 bg-base-300 flex items-center px-4 select-none drag">
    <div class="flex items-center gap-2 flex-1">
      <img src="../assets/logo.png" class="w-5 h-5 no-drag" alt="logo" />
      <span class="font-semibold text-sm">ClipMate</span>
    </div>
    <div class="flex items-center no-drag">
      <button 
        class="btn btn-ghost btn-sm px-2" 
        @click="appStore.toggleTheme"
        :title="appStore.theme === 'light' ? '切换到暗色主题' : '切换到亮色主题'"
      >
        <i :class="appStore.theme === 'light' ? 'ri-moon-line' : 'ri-sun-line'"></i>
      </button>
      <button class="btn btn-ghost btn-sm px-2" @click="minimizeWindow">
        <i class="ri-subtract-line"></i>
      </button>
      <button class="btn btn-ghost btn-sm px-2" @click="toggleMaximize">
        <i :class="isMaximized ? 'ri-checkbox-multiple-line' : 'ri-checkbox-blank-line'"></i>
      </button>
      <button class="btn btn-ghost btn-sm px-2 hover:bg-error hover:text-error-content" @click="closeWindow">
        <i class="ri-close-line"></i>
      </button>
    </div>
  </div>
</template>

<style scoped>
.drag {
  -webkit-app-region: drag;
}

.no-drag {
  -webkit-app-region: no-drag;
}
</style> 